package com.qdaily.ui.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.qdaily.supportlibrary.util.BitmapUtil;
import com.qdaily.supportlibrary.util.LocalDisplay;
import com.qdaily.ui.PhotoChoose.CropOption;
import com.qdaily.ui.QDBaseActivity;
import com.qdaily.ui.R;
import com.qdaily.ui.ui.views.QDWebView.QDArticleWebViewFileCache.QDArticleWebViewFileCacheMgr;
import com.qdaily.ui.ui.views.TitleBar;

import java.io.File;

import uk.co.senab.photoview.PhotoView;

/**
 * Created by song on 15/5/26.
 */
public class ImageCropActivity extends QDBaseActivity implements ViewTreeObserver.OnGlobalLayoutListener {

    public static final String KeyTitleString = "KeyTitleString";
    public static final String KeyCropStyle = "KeyCorpStyle";
    public static final String KeyResultImagePath = "KeyResultImagePath";

    ImageView cover;
    PhotoView image;
    View container;

    Bitmap sourceBmp;

    private String title;

    private CropOption.CropStyle style;
    private File imageCropOutPutFile;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_imagecrop);
        title = getIntent().getStringExtra(KeyTitleString);
        if (title == null) {
            title = getString(R.string.imagecrop_title);
        }
        style = (CropOption.CropStyle) getIntent().getSerializableExtra(KeyCropStyle);
        if (style == null) {
            style = CropOption.CropStyle.CropStyleDefault;
        }
        imageCropOutPutFile = (File) getIntent().getSerializableExtra(KeyResultImagePath);
        if (imageCropOutPutFile == null) {
            imageCropOutPutFile = new File(QDArticleWebViewFileCacheMgr.getInstance().CacheFilePath, Long.toString(System.nanoTime()) + "_cropped.jpg");
        }
        initView();
    }

    protected void initView() {

        TitleBar titleBar = (TitleBar) this.findViewById(R.id.imagecrop_tilte);
        titleBar.setTitle(title);
        titleBar.onBack();
        titleBar.setRightText("完成");
        titleBar.setRightTextViewOnclickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                crop(view);
            }
        });

        container = findViewById(R.id.container);
        image = (PhotoView) findViewById(R.id.img);
        cover = (ImageView) findViewById(R.id.cover);

        Uri uri = getIntent().getData();
        sourceBmp = BitmapUtil.getBitmap(this, uri);
        image.setImageBitmap(sourceBmp);

        cover.getViewTreeObserver().addOnGlobalLayoutListener(this);
    }

    public void crop(View view) {
        showLoading();
        new CropTask().execute();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        dismissLoading();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (sourceBmp != null) {
            sourceBmp.recycle();
        }
    }

    class CropTask extends AsyncTask<Void, Void, Object[]> {

        @Override
        protected void onPostExecute(Object[] result) {
            // TODO Auto-generated method stub
            Intent data = getIntent();
            data.putExtra(KeyResultImagePath, (File) result[0]);
            setResult(RESULT_OK, data);
            finish();
        }

        @Override
        protected Object[] doInBackground(Void... params) {
            // TODO Auto-generated method stub
            container.destroyDrawingCache();
            container.setDrawingCacheEnabled(true);
            Bitmap bmp = container.getDrawingCache();
            if (style == CropOption.CropStyle.CropStyleDefault) {
                bmp = BitmapUtil.getRoundIcon(bmp, CircleRadius - 1);
            } else if (style == CropOption.CropStyle.CropStyleSquare) {
                bmp = BitmapUtil.getSquareIcon(bmp);
            }

            BitmapUtil.saveBmp(bmp, imageCropOutPutFile);
            Object[] objs = new Object[1];
            objs[0] = imageCropOutPutFile;
            bmp.recycle();
            return objs;
        }

    }


    public Bitmap getCoverBmp() {
        if (style == CropOption.CropStyle.CropStyleNone) {
            return null;
        }

        int scale = 2;

        Bitmap bmp = Bitmap.createBitmap(width / scale, height / scale, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bmp);
        canvas.drawARGB(0x7f, 0, 0, 0);

        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        if (style == CropOption.CropStyle.CropStyleDefault) {
            canvas.drawCircle(width / (2 * scale), height / (2 * scale), (CircleRadius + 1) / scale, paint);
        } else if (style == CropOption.CropStyle.CropStyleSquare) {
            canvas.drawRect(0, (height - width) / (2 * scale), width / scale, (height - width) / (2 * scale) + width / scale, paint);
        }
        return bmp;
    }

    int width, height;

    @Override
    public void onGlobalLayout() {
        // TODO Auto-generated method stub
        width = LocalDisplay.SCREEN_WIDTH_PIXELS;
        height = container.getHeight();

        calRadius();
        cover.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        cover.setImageBitmap(getCoverBmp());

        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LocalDisplay.SCREEN_WIDTH_PIXELS, LocalDisplay.SCREEN_WIDTH_PIXELS);
        lp.setMargins(0, (height - LocalDisplay.SCREEN_WIDTH_PIXELS) / 2, 0, 0);
        image.setLayoutParams(lp);
    }


    private void calRadius() {
        // TODO Auto-generated method stub
        if (style == CropOption.CropStyle.CropStyleDefault) {
            CircleRadius = width / 2 - getResources().getDimensionPixelSize(R.dimen.circle_margin);
        }

    }

    public static int CircleRadius;
}
